chalk = require('chalk')
pg = require('pg')
Query = pg.Query
submit = Query::submit
format = require('pg-format')

Query::submit = ->
  text = @text
  if @values
      text = @values.reduce(
        (q, v, i) ->
            return q.replace "$#{i+1}", format.literal(v)
        text
      )
  begin = new Date()
  log = ->
      t = [
        chalk.yellow("psql")
        chalk.gray("<")
        chalk.yellowBright(text)
      ]
      cost = (new Date() - begin)
      if cost > 10
            t.push chalk.gray((cost / 1000) + " 秒")
      console.log  t.join(" ")
  try
      r = submit.apply(@, arguments)
  finally
      log()
  return r
